"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _icon = _interopRequireDefault(require("../../../icon"));

var _configContext = require("../../../../extends/configContext");

var _fingerWeb = _interopRequireDefault(require("../../libs/finger-web"));

var _mouseWeb = _interopRequireDefault(require("../../libs/mouse-web"));

var _get = require("../../../../utils/get");

var _spin = _interopRequireDefault(require("../../../spin"));

var _isMobile = _interopRequireDefault(require("../../../../utils/is-mobile"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var WebImgPreviewerViewer = function WebImgPreviewerViewer(_ref) {
  var _ref$imgUrls = _ref.imgUrls,
      imgUrls = _ref$imgUrls === void 0 ? [] : _ref$imgUrls,
      _ref$currentImgIdx = _ref.currentImgIdx,
      currentImgIdx = _ref$currentImgIdx === void 0 ? 0 : _ref$currentImgIdx,
      _ref$visible = _ref.visible,
      visible = _ref$visible === void 0 ? false : _ref$visible,
      _ref$onClose = _ref.onClose,
      onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
      _ref$onSwipRight = _ref.onSwipRight,
      onSwipRight = _ref$onSwipRight === void 0 ? function () {} : _ref$onSwipRight,
      _ref$onSwipLeft = _ref.onSwipLeft,
      onSwipLeft = _ref$onSwipLeft === void 0 ? function () {} : _ref$onSwipLeft,
      _ref$onClickLock = _ref.onClickLock,
      onClickLock = _ref$onClickLock === void 0 ? function () {} : _ref$onClickLock,
      _ref$onClickUnLock = _ref.onClickUnLock,
      onClickUnLock = _ref$onClickUnLock === void 0 ? function () {} : _ref$onClickUnLock,
      _ref$onError = _ref.onError,
      _onError = _ref$onError === void 0 ? function (i) {
    return '';
  } : _ref$onError;

  var IS_MOBILE = false;

  if (typeof window !== 'undefined') {
    IS_MOBILE = (0, _isMobile.default)();
  }

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix; // 事件中心


  var fingerEventCenter = _react.default.useRef(null);

  var mouseEventCenter = _react.default.useRef(null); // tap 事件守卫


  var doubleTapFlag = _react.default.useRef(false);

  var doubleTapFlagTimer = _react.default.useRef(null); // pinch 事件守卫


  var pinchFlag = _react.default.useRef(false);

  var pinchFlagTimer = _react.default.useRef(null); // swipe 事件守卫


  var swipeFlag = _react.default.useRef(false);

  var swipeFlagTimer = _react.default.useRef(null); // pressMove 事件守卫


  var pressMoveFlag = _react.default.useRef(false);

  var pressMoveFlagTimer = _react.default.useRef(null); // 下滑事件守卫


  var click = _react.default.useRef(false);

  var clickTimer = _react.default.useRef(null);

  var imgType = _react.default.useRef('normal'); // 图片引用


  var imgRef = _react.default.useRef(null); // 当前图片列表和引用数的 ref


  var currentImgIndexRef = _react.default.useRef(currentImgIdx);

  var imgUrlsRef = _react.default.useRef(imgUrls); // 图像长宽控制


  var _React$useState = _react.default.useState(null),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      imageWidth = _React$useState2[0],
      setImageWidth = _React$useState2[1];

  var _React$useState3 = _react.default.useState(null),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      imageHeight = _React$useState4[0],
      setImageHeight = _React$useState4[1]; // 图像加载状态控制


  var _React$useState5 = _react.default.useState(false),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      isImageLoading = _React$useState6[0],
      setImageLoadingState = _React$useState6[1];

  var _React$useState7 = _react.default.useState(false),
      _React$useState8 = _slicedToArray(_React$useState7, 2),
      isImageLoadError = _React$useState8[0],
      setIsImageLoadError = _React$useState8[1]; // 缩放比率及模式控制


  var _React$useState9 = _react.default.useState(false),
      _React$useState10 = _slicedToArray(_React$useState9, 2),
      scaleMode = _React$useState10[0],
      setScaleMode = _React$useState10[1];

  var _React$useState11 = _react.default.useState(1),
      _React$useState12 = _slicedToArray(_React$useState11, 2),
      scaleRate = _React$useState12[0],
      setScaleRate = _React$useState12[1]; // 图像位移控制


  var _React$useState13 = _react.default.useState(0),
      _React$useState14 = _slicedToArray(_React$useState13, 2),
      deltaY = _React$useState14[0],
      setDeltaY = _React$useState14[1];

  var _React$useState15 = _react.default.useState(0),
      _React$useState16 = _slicedToArray(_React$useState15, 2),
      deltaX = _React$useState16[0],
      setDeltaX = _React$useState16[1]; // 图像缩放原点控制


  var _React$useState17 = _react.default.useState(0),
      _React$useState18 = _slicedToArray(_React$useState17, 2),
      zoomX = _React$useState18[0],
      setZoomX = _React$useState18[1];

  var _React$useState19 = _react.default.useState(0),
      _React$useState20 = _slicedToArray(_React$useState19, 2),
      zoomY = _React$useState20[0],
      setZoomY = _React$useState20[1]; // 是否为长图模式


  var _React$useState21 = _react.default.useState(false),
      _React$useState22 = _slicedToArray(_React$useState21, 2),
      isLongPic = _React$useState22[0],
      setIsLongPic = _React$useState22[1]; // 图像 zoom 偏移量修复


  var _React$useState23 = _react.default.useState(0),
      _React$useState24 = _slicedToArray(_React$useState23, 2),
      zoomPositionX = _React$useState24[0],
      setZoomPositionX = _React$useState24[1];

  var _React$useState25 = _react.default.useState(0),
      _React$useState26 = _slicedToArray(_React$useState25, 2),
      zoomPositionY = _React$useState26[0],
      setZoomPositionY = _React$useState26[1]; // 当前图像的 url


  var _React$useState27 = _react.default.useState(imgUrls[currentImgIdx] || ''),
      _React$useState28 = _slicedToArray(_React$useState27, 2),
      currImgUrl = _React$useState28[0],
      setCurrImgUrl = _React$useState28[1];

  var firstLoadRef = _react.default.useRef(true);

  var viewerRef = _react.default.useRef(null);

  var transformStyle = {};
  var windowHeight = 600;

  if (typeof window !== 'undefined') {
    windowHeight = window.innerHeight;
  }

  var scaleModeHandler = _react.default.useCallback(function (_ref2) {
    var _ref2$noZoomPositionC = _ref2.noZoomPositionChange,
        noZoomPositionChange = _ref2$noZoomPositionC === void 0 ? false : _ref2$noZoomPositionC;
    setScaleMode(function (currentMode) {
      var isErrorOrLoading = false;
      setIsImageLoadError(function (errorState) {
        if (errorState) isErrorOrLoading = true;
        return errorState;
      });
      setImageLoadingState(function (loading) {
        if (loading) isErrorOrLoading = true;
        return loading;
      });
      if (isErrorOrLoading) return;

      if (currentMode) {
        setScaleRate(1);

        if (imgType.current !== 'long') {
          setDeltaX(0);
          setDeltaY(0);
        } else {
          setDeltaX(0);
        }

        if (!noZoomPositionChange) {
          setZoomX(0);
          setZoomY(0);
        }
      } else {
        setScaleRate(2);
      }

      return !currentMode;
    });
  }, []);

  var lockSingleTap = _react.default.useCallback(function () {
    if (doubleTapFlagTimer.current) {
      clearTimeout(doubleTapFlagTimer.current);
    }

    doubleTapFlag.current = true;
    doubleTapFlagTimer.current = setTimeout(function () {
      doubleTapFlag.current = false;
    }, 300);
  }, []);

  var lockPressMove = _react.default.useCallback(function () {
    if (pressMoveFlag.current) {
      clearTimeout(pressMoveFlagTimer.current);
    }

    pressMoveFlag.current = true;
    pressMoveFlagTimer.current = setTimeout(function () {
      pressMoveFlag.current = false;
    }, 300);
  }, []); // 锁定 click 事件，防止由于 click 导致的穿透问题


  var lockClick = _react.default.useCallback(function () {
    if (click.current) {
      clearTimeout(clickTimer.current);
    }

    click.current = true;
    onClickLock();
    clickTimer.current = setTimeout(function () {
      click.current = false;
      onClickUnLock();
    }, 300);
  }, []); // pinch 锁，100 ms，最小可能出现定位点错误问题


  var lockPinch = _react.default.useCallback(function () {
    clearTimeout(pinchFlagTimer.current);
    pinchFlag.current = true;
    pinchFlagTimer.current = setTimeout(function () {
      pinchFlag.current = false;
    }, 500);
  }, []);

  var lockSwipe = _react.default.useCallback(function () {
    if (swipeFlag.current) return;
    swipeFlag.current = true;
    swipeFlagTimer.current = setTimeout(function () {
      swipeFlag.current = false;
    }, 300);
  }, []);
  /**
   * 聚焦函数，会出现偏移的情况
   */


  var focusOnTargetPosition = (0, _react.useCallback)(function (_ref3) {
    var x = _ref3.x,
        y = _ref3.y;
    if (!imgRef.current) return;
    var deltaX = null;
    var deltaY = null;
    var scaleRate = null;
    var offsetLeft = imgRef.current.getBoundingClientRect().left;
    var offsetTop = imgRef.current.getBoundingClientRect().top; // 获取当前的 rate、x、y 轴偏移量

    setScaleRate(function (rate) {
      scaleRate = rate;
      return rate;
    });
    setDeltaX(function (x) {
      deltaX = x;
      return x;
    });
    setDeltaY(function (y) {
      deltaY = y;
      return y;
    });

    if (typeof window !== 'undefined') {
      var imagePositionX = (x - offsetLeft) / scaleRate;
      var imagePositionY = (y - offsetTop) / scaleRate;
      setZoomX(function () {
        return imagePositionX;
      });
      setZoomY(function () {
        return imagePositionY;
      });
    }
  }, []);

  var swipeLeftImpl = _react.default.useCallback(function () {
    setScaleMode(function (scaleMode) {
      if (scaleMode) return scaleMode;

      if (currentImgIndexRef.current + 1 !== imgUrlsRef.current.length) {
        setImageLoadingState(true);
      }

      onSwipLeft();
      setTimeout(function () {
        setDeltaX(0);
        setDeltaY(0);
      }, 300);
      return scaleMode;
    });
  }, [onSwipLeft]);

  var swipeRightImpl = _react.default.useCallback(function () {
    setScaleMode(function (scaleMode) {
      if (scaleMode) return scaleMode;

      if (currentImgIndexRef.current + 1 !== 1) {
        setImageLoadingState(true);
      }

      onSwipRight();
      setTimeout(function () {
        setDeltaX(0);
        setDeltaY(0);
      }, 300);
      return scaleMode;
    });
  }, [onSwipRight]);

  (0, _react.useEffect)(function () {
    if (viewerRef.current) {
      fingerEventCenter.current = new _fingerWeb.default(viewerRef.current, {
        singleTap: function singleTap() {
          if (!doubleTapFlag.current) {
            onClose();
          }
        },
        doubleTap: function doubleTap(evt) {
          var pageX = (0, _get.get)(evt.changedTouches[0], 'pageX', 0);
          var pageY = (0, _get.get)(evt.changedTouches[0], 'pageY', 0);
          focusOnTargetPosition({
            x: pageX,
            y: pageY
          });
          scaleModeHandler({
            noZoomPositionChange: true
          });
        },
        // pinch 事件暂时注释
        pinch: function pinch(evt) {
          // pinch 的时候锁定 tap 和 swipe 事件，防止发生缩放时被关闭和切换
          lockSingleTap();
          lockSwipe();
          setScaleMode(true); // 这里也锁定下 pressmove 事件，防止误触

          lockPressMove();
          var pageX = ((0, _get.get)(evt.touches[0], 'pageX', 0) + (0, _get.get)(evt.touches[1], 'pageX', 0)) / 2;
          var pageY = ((0, _get.get)(evt.touches[0], 'pageY', 0) + (0, _get.get)(evt.touches[1], 'pageY', 0)) / 2;

          if (evt.zoom > 1 && !pinchFlag.current) {
            if (evt.zoom <= 2.5) {
              focusOnTargetPosition({
                x: pageX,
                y: pageY
              });
              lockPinch();
            }
          } // 最小缩放比例 1，采用固定缩小比例


          if (Number(evt.zoom) <= 1) {
            setScaleRate(function (rate) {
              if (0.85 * rate <= 1) {
                setDeltaX(0);

                if (imgType.current !== 'long') {
                  setDeltaY(0);
                }

                setScaleMode(false);
                return 1;
              }

              return 0.85 * rate;
            });
            return;
          } // 最大缩放比例 3


          setScaleRate(function (rate) {
            if (rate >= 3) return rate;

            if (evt.zoom < rate) {
              return rate + evt.zoom / 3;
            }

            return (evt.zoom - rate) / 3 + rate;
          });
        },
        pressMove: function pressMove(evt) {
          lockSingleTap(); // 如果此时处于事件加锁阶段，不执行

          if (pressMoveFlag.current) return;

          var deltaYSetter = function deltaYSetter() {
            setDeltaY(function (currentY) {
              var windowHeight = window.innerHeight;
              if (!imgRef.current) return; // 顶部和底部余量，用来在滑动边缘值时进行修正

              var topAllowance = imgRef.current.getBoundingClientRect().top;
              var bottomAllowance = imgRef.current.getBoundingClientRect().bottom - windowHeight + 89;
              var isTopEnd = topAllowance >= 0;
              var isBottomEnd = bottomAllowance <= 0;

              if (evt.deltaY >= 0) {
                if (isTopEnd) {
                  // 触顶下拉 close 事件
                  if (evt.deltaY >= 30) {
                    onClose();
                  }

                  return currentY;
                }

                if (topAllowance <= 0 && -topAllowance <= evt.deltaY) {
                  return currentY + Math.abs(topAllowance);
                }
              }

              if (evt.deltaY < 0) {
                if (isBottomEnd) {
                  return currentY;
                }

                if (bottomAllowance >= 0 && bottomAllowance <= Math.abs(evt.deltaY)) {
                  return currentY - bottomAllowance;
                }
              }

              return currentY + evt.deltaY;
            });
          };

          var deltaXSetter = function deltaXSetter() {
            setDeltaX(function (currentX) {
              var windowWidth = window.innerWidth;
              var rate = 1;
              setScaleRate(function (currentRate) {
                rate = currentRate;
                return rate;
              });
              if (!imgRef.current) return; // 左侧和右侧的余量，用来在滑动边缘值时进行修正

              var leftAllowance = imgRef.current.getBoundingClientRect().left;
              var rightAllowance = imgRef.current.getBoundingClientRect().right - windowWidth;
              var isLeftEnd = leftAllowance >= 0;
              var isRightEnd = rightAllowance <= 0;

              if (evt.deltaX >= 0) {
                if (leftAllowance <= 0 && Math.abs(leftAllowance) <= evt.deltaX) {
                  return currentX + Math.abs(leftAllowance);
                } // 边缘组织


                if (isLeftEnd) {
                  if (Math.abs(evt.deltaX) > 15) {
                    if (swipeFlag.current) return;
                    lockSwipe();
                    setScaleMode(false);
                    swipeRightImpl();
                  }

                  ;
                  return currentX;
                }

                ; // // 进行余量修正
                // if (leftAllowance > 0) {
                //   return currentX - leftAllowance;
                // }
              }

              if (evt.deltaX < 0) {
                if (rightAllowance >= 0 && rightAllowance <= Math.abs(evt.deltaX)) {
                  return currentX + rightAllowance;
                }

                if (isRightEnd) {
                  if (Math.abs(evt.deltaX) > 15) {
                    if (swipeFlag.current) return;
                    lockSwipe();
                    setScaleMode(false);
                    swipeLeftImpl();
                  }

                  ;
                  return currentX;
                } // // 进行余量修正
                // if (rightAllowance <= 0) {
                //   return currentX - rightAllowance;
                // }

              }

              return currentX + evt.deltaX;
            });
          };

          setScaleMode(function (scaleMode) {
            if (scaleMode) {
              deltaXSetter();
              deltaYSetter();
              return scaleMode;
            }

            setImageHeight(function (height) {
              var windowHeight = window.innerHeight;
              var IS_LONG_PIC_MODE = height > windowHeight - 89;

              if (IS_LONG_PIC_MODE) {
                deltaYSetter();
              } else {
                if (evt.deltaY >= 30) {
                  // 下拉关闭手势
                  onClose();
                }
              }

              setImageHeight(height);
            });
            return scaleMode;
          });
        },
        swipe: function swipe(evt) {
          lockSingleTap();
          lockPressMove();

          if (swipeFlag.current) {
            return;
          }

          switch (evt.direction) {
            case 'Left':
              swipeLeftImpl();
              break;

            case 'Right':
              swipeRightImpl();
          }
        }
      });
      mouseEventCenter.current = new _mouseWeb.default(viewerRef.current, {
        mouseMove: function mouseMove(evt) {
          if (!imgRef.current) return;
          var windowWidth = window.innerWidth;
          var windowHeight = window.innerHeight; // 左侧和右侧的余量，用来在滑动边缘值时进行修正

          var leftAllowance = imgRef.current.getBoundingClientRect().left;
          var rightAllowance = imgRef.current.getBoundingClientRect().right - windowWidth;
          var topAllowance = imgRef.current.getBoundingClientRect().top;
          var bottomAllowance = imgRef.current.getBoundingClientRect().bottom - windowHeight + 80;
          var isTopEnd = topAllowance >= 0;
          var isBottomEnd = bottomAllowance <= 0;
          var isLeftEnd = leftAllowance >= 0;
          var isRightEnd = rightAllowance <= 0; // 锁定 click 事件，防止 click 导致的意外关闭

          lockClick();
          evt.preventDefault();
          evt.stopPropagation();
          setScaleMode(function (scaleMode) {
            if (scaleMode) {
              setDeltaX(function (currentX) {
                return (// if (evt.deltaX < 0) {
                  //   if (isLeftEnd) {
                  //     return currentX;
                  //   }
                  // }
                  // if (evt.deltaX >= 0) {
                  //   if (isRightEnd) {
                  //     return currentX;
                  //   }
                  // }
                  currentX + evt.deltaX
                );
              });
              setDeltaY(function (currentY) {
                return (// if (evt.deltaY < 0) {
                  //   if (isBottomEnd) {
                  //     return currentY;
                  //   }
                  // }
                  // if (evt.deltaY >= 0) {
                  //   if (isTopEnd) {
                  //     return currentY;
                  //   }
                  // }
                  currentY + evt.deltaY
                );
              });
              return scaleMode;
            }

            setImageHeight(function (height) {
              var windowHeight = window.innerHeight;
              var IS_LONG_PIC_MODE = height > windowHeight - 89;

              if (IS_LONG_PIC_MODE) {
                setIsLongPic(true);
                setDeltaY(function (currentY) {
                  return (// if (evt.deltaY < 0) {
                    //   if (isBottomEnd) {
                    //     return currentY;
                    //   }
                    // }
                    // if (evt.deltaY >= 0) {
                    //   if (isTopEnd) {
                    //     return currentY;
                    //   }
                    // }
                    currentY + evt.deltaY
                  );
                });
              }

              setImageHeight(height);
            });
          });
        },
        zoomIn: function zoomIn(_ref4) {
          var zoom = _ref4.zoom,
              evt = _ref4.evt;
          setScaleMode(true);
          setScaleRate(function (rate) {
            if (rate - zoom / 10 <= 1) {
              // setScaleMode(false);
              return 1;
            }

            return rate - zoom / 10;
          });
        },
        zoomOut: function zoomOut(_ref5) {
          var zoom = _ref5.zoom,
              evt = _ref5.evt;
          setScaleRate(function (rate) {
            return rate + zoom / 10;
          });
          focusOnTargetPosition({
            x: evt.x,
            y: evt.y
          });
          setScaleMode(true);
        }
      });
    }

    return function () {
      if (fingerEventCenter.current) {
        fingerEventCenter.current.destroy();
      }

      if (mouseEventCenter.current) {
        mouseEventCenter.current.destroy();
      }
    };
  }, []);
  (0, _react.useEffect)(function () {
    setIsLongPic(false);
    var loadingStateTimer = null;
    var urlChangeTimer = null;

    if (!firstLoadRef.current) {
      setImageLoadingState(true);
    }

    firstLoadRef.current = false;
    currentImgIndexRef.current = currentImgIdx;
    imgUrlsRef.current = imgUrls;
    urlChangeTimer = setTimeout(function () {
      setCurrImgUrl(imgUrls[currentImgIdx]);
      setIsImageLoadError(false);
      setScaleMode(false);
      setZoomX(0);
      setZoomY(0);
    }, 300);
    loadingStateTimer = setTimeout(function () {
      if (!imgRef.current) {
        setIsImageLoadError(true);
        setImageLoadingState(false);
        return;
      }

      if (imgRef.current && imgRef.current.complete || isImageLoadError) {
        setImageLoadingState(false);
      } else {
        setImageLoadingState(true);
      }
    }, 300);
    return function () {
      clearTimeout(loadingStateTimer);
      clearTimeout(urlChangeTimer);
    };
  }, [currentImgIdx]);

  if (imageWidth) {
    Object.assign(transformStyle, {
      width: imageWidth
    });
  }

  if (imageHeight) {
    Object.assign(transformStyle, {
      height: imageHeight
    });
  }

  if (isImageLoading) {
    Object.assign(transformStyle, {
      visibility: 'hidden',
      opacity: 0
    });
  } else {
    Object.assign(transformStyle, {
      visibility: 'visible',
      opacity: 1
    });
  }

  if (windowHeight - 89 < imageHeight) {
    Object.assign(transformStyle, {
      top: "calc(50% + ".concat(deltaY, "px)")
    });
  }

  if (scaleMode) {
    Object.assign(transformStyle, {
      transform: "translate(-50%, -50%) scale(".concat(scaleRate, ") translateZ(0)"),
      top: "calc(50% + ".concat(deltaY, "px)"),
      left: "calc(50% + ".concat(deltaX, "px)")
    });
  }

  if (zoomX && zoomY) {
    Object.assign(transformStyle, {
      transformOrigin: "".concat(zoomX, "px ").concat(zoomY, "px")
    });
  }

  var computeSize = function computeSize(_ref6) {
    var height = _ref6.height,
        width = _ref6.width;

    if (typeof window !== 'undefined') {
      var mode = 'width';
      var rate = 1;

      if (height >= width) {
        mode = 'height';
      }

      var _windowHeight = window.innerHeight;
      var windowWidth = window.innerWidth;

      switch (mode) {
        case 'width':
          setDeltaY(0);
          setDeltaX(0);

          if (width > windowWidth) {
            rate = width / windowWidth;
            setImageWidth(windowWidth);
            setImageHeight(height / rate);
            imgType.current = 'width';
          } else {
            setImageWidth(width);
            setImageHeight(height);
            imgType.current = 'normal';
          }

          break;

        case 'height':
          if (height >= _windowHeight) {
            var IS_LONG_PIC = height / width >= 2.5;

            if (IS_LONG_PIC) {
              setIsLongPic(true);

              if (width <= windowWidth) {
                setImageWidth(width);
                setImageHeight(height); // TODO: 这里处理了长图固定顶部的逻辑，但是这里的耦合度很高

                setDeltaY(height / 2 - _windowHeight / 2);
                imgType.current = 'long';
              } else {
                setImageWidth(windowWidth);
                rate = width / windowWidth;
                setImageHeight(height / rate); // TODO: 这里处理了长图固定顶部的逻辑，但是这里的耦合度很高

                setDeltaY(height / rate / 2 - _windowHeight / 2);
                imgType.current = 'long';
              }
            } else {
              setIsLongPic(false);
              setDeltaY(0);
              setDeltaX(0);

              if (width >= windowWidth) {
                setImageWidth(windowWidth);
                rate = width / windowWidth;
                setImageHeight(height / rate);
                imgType.current = 'normal';
              } else {
                rate = height / _windowHeight;
                setImageHeight(_windowHeight);
                setImageWidth(width / rate);
                imgType.current = 'normal';
              }
            }
          } else {
            setIsLongPic(false);
            setDeltaY(0);
            setDeltaX(0);

            if (width >= windowWidth) {
              setImageWidth(windowWidth);
              rate = width / windowWidth;
              setImageHeight(height / rate);
            } else {
              // rate = height / windowHeight;
              // setImageHeight(windowHeight);
              // setImageWidth(width / rate);
              setImageWidth(width);
              setImageHeight(height);
            }

            imgType.current = 'normal';
          }

          break;
      }
    }
  };

  var renderStatus = function renderStatus() {
    if (isImageLoading) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(clsPrefix, "-img-previewer__viewer-loading")
      }, /*#__PURE__*/_react.default.createElement(_spin.default, {
        type: 'spinner'
      }));
    }

    if (isImageLoadError) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(clsPrefix, "-img-previewer__viewer-loading is-error")
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        name: "PictureErrorOutlined",
        size: 50
      }), "\u56FE\u50CF\u52A0\u8F7D\u5931\u8D25");
    }

    return null;
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-img-previewer__viewer-wrapper"),
    ref: viewerRef
  }, !isImageLoadError && /*#__PURE__*/_react.default.createElement("img", {
    style: transformStyle,
    ref: imgRef,
    draggable: false,
    onLoad: function onLoad(e) {
      computeSize({
        height: e.target.naturalHeight,
        width: e.target.naturalWidth
      });
      setTimeout(function () {
        setImageLoadingState(false);
      }, 300);
    },
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();
    },
    onError: function onError(e) {
      // 图片错误，进行错误处理，如果需要重置则重置报错
      var newUrl = _onError(currentImgIdx);

      if (newUrl && newUrl !== currImgUrl) {
        setCurrImgUrl(newUrl);
        return;
      }

      setImageLoadingState(false);
      setIsImageLoadError(true);
    },
    onDoubleTap: function onDoubleTap(e) {
      e.stopPropagation();
      e.preventDefault();
    },
    onTap: function onTap(e) {
      e.stopPropagation();
      e.preventDefault();
    },
    onDoubleClick: function onDoubleClick() {
      if (!IS_MOBILE) {
        scaleModeHandler({
          noZoomPositionChange: false
        });
      }
    },
    className: (0, _classnames.default)("".concat(clsPrefix, "-img-previewer__viewer-instance"), {
      'is-hidden': isImageLoading,
      'is-movable': scaleMode || isLongPic
    }),
    src: currImgUrl
  }), renderStatus());
};

var _default = WebImgPreviewerViewer;
exports.default = _default;